import { FC } from "react";
import { Menu } from "antd";
import type { MenuProps } from "antd";
import { RouteRawState } from "../../types";
import { useNavigate, useLocation } from "react-router-dom";
import { useSelector } from "react-redux";
import { RootState } from "../../store";
type PropsType = {
  routes: RouteRawState[];
};
const generatorNavItems = (
  routes: RouteRawState[],
  role: string
): MenuProps["items"] => {
  return routes
    .filter(v => {
      if (v.hidden) {
        return false;
      } else {
        if (role === "admin") return true;
        if (!v.meta.role) return true;
        return v.meta.role.includes(role);
      }
    })
    .map(v => {
      return {
        key: v.path,
        label: v.meta.title,
        icon: v.meta.icon,
        children: v.children && generatorNavItems(v.children, role),
      };
    });
};
export const SliderNav: FC<PropsType> = ({ routes }) => {
  const role = useSelector((state: RootState) => state.user.role);
  const items: MenuProps["items"] = generatorNavItems(routes, role);
  const navigate = useNavigate();
  const { pathname } = useLocation();
  return (
    <div>
      <Menu
        mode="inline"
        defaultSelectedKeys={[pathname]}
        defaultOpenKeys={["sub1"]}
        style={{ height: "100%" }}
        onClick={({ key }) => navigate(key)}
        items={items}
      />
    </div>
  );
};
